package com.echo.distributedlock.api;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.lang.Nullable;

import javax.sql.DataSource;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @author lmy
 */
public class DbLock implements Lock {

    private final String key;

    private final DataSource dataSource;

    @Override
    public void lock() {
        throw new IllegalArgumentException();
    }

    @Override
    public void lockInterruptibly() {
        throw new IllegalArgumentException();
    }

    @Override
    public boolean tryLock() {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        String sql = String.format("INSERT INTO `ECHO_LOCK` (`key`) VALUES ('%s');", key);
        try {
            int update = jdbcTemplate.update(sql);
            return update > 0;
        }catch (Exception ignored) {

        }
        return false;
    }

    @Override
    public boolean tryLock(long time, @Nullable TimeUnit unit) {
        return false;
    }

    @Override
    public void unlock() {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        String sql = String.format("DELETE FROM `ECHO_LOCK` WHERE `key` = '%s';", key);
        jdbcTemplate.update(sql);
    }

    @Override
    public Condition newCondition() {
        throw new IllegalArgumentException();
    }

    public DbLock(String key, DataSource dataSource) {
        this.key = key;
        this.dataSource = dataSource;
    }
}
